
from rest_framework.response import Response
from rest_framework.views import APIView
import json
from .serializer import BookSerializer
from books.models import BookInfo


class Books(APIView):
    def get(self, request):
        print(request.query_params)
        books = BookInfo.objects.all()
        ser = BookSerializer(books, many=True)
        return Response(ser.data)

    def post(self, request):
        # data = request.body.decode()
        # data_dict = json.loads(data)
        data_dict = request.data
        # 验证数据
        ser = BookSerializer(data=data_dict)
        # 修改时
        # ser = BooksSerializer('查询集对象', data=data_dict)
        # 验证错误直接报错
        ser.is_valid(raise_exception=True)
        # 获取验证成功后的字段
        # print(ser.validated_data)
        # 保存书据 看序列类参数是否传递　决定创建还是更改
        ser.save()
        # 响应
        return Response(ser.data)

class Book(APIView):
    def put(self, request, pk):
        data = request.body.decode()
        data_dict = json.loads(data)
        try:
            book = BookInfo.objects.get(pk=pk)
        except:
            return Response('错误')
        # 验证数据
        # ser = BooksSerializer(data=data_dict)
        # 修改时
        ser = BookSerializer('查询集对象', data=data_dict)
        # 验证错误直接报错
        ser.is_valid(raise_exception=True)
        # 获取验证成功后的字段
        # print(ser.validated_data)
        # 保存书据 看序列类参数是否传递　决定创建还是更改
        ser.save()
        # 响应
        return Response(ser.data)